import path from 'path';
import { existsSync, rmSync } from 'fs';
import inquirer from 'inquirer';
import { wrapLoading } from '../utils/loading.js';
import {
  getProject,
  getProjectBranch,
  downloadProject,
} from '../utils/project.js';

export default async (name, options) => {
  console.log(name, options, 'cmd');
  // 当前工作目录
  const cwd = process.cwd();
  // 拼接到当前 输入的目录名称（工程名称）
  const targetDir = path.join(cwd, name);

  if (existsSync(targetDir)) {
    if (options.force) {
      // 递归删除该目录
      rmSync(targetDir, { recursive: true });
    } else {
      // inquirer.prompt 会返回 自定义的 action 作为用户选择的choices 中 value值
      let { action } = await inquirer.prompt([
        {
          name: 'action',
          type: 'list',
          message: '目录已存在，请选择操作',
          choices: [
            { name: 'overwrite', value: 'overwrite' },
            { name: 'cancel', value: 'cancel' },
          ],
        },
      ]);

      if (action === 'cancel') {
        console.log('用户取消创建');
        return;
      }
      if (action === 'overwrite') {
        wrapLoading('删除之前的目录中', () => {
          rmSync(targetDir, { recursive: true });
          console.log('删除成功');
        });
      }
    }
  }

  // 获取项目仓库，拉取对应的项目
  const projectName = await getProject();
  let { project } = await inquirer.prompt([
    {
      name: 'project',
      type: 'list',
      message: '请选择项目列表',
      choices: projectName,
    },
  ]);

  const branchName = await getProjectBranch(project);

  let { branchs } = await inquirer.prompt([
    {
      name: 'branchs',
      type: 'list',
      message: '请选择分支',
      choices: branchName,
    },
  ]);

  wrapLoading('下载模板中', () => {
    downloadProject(project, branchs);
  });
};
